/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pfc.core.web;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author xandru
 */
public class Pager<T> {

    final private int DEFAULT_PAGE_SIZE=10;
    private List<T> _list;
    private int pageSize;
    private int currentPage;
    private int lastPage;

    public Pager(List<T> l)
    {
       _list = l;
        this.pageSize = DEFAULT_PAGE_SIZE;
        currentPage=1;
        lastPage = (l.size()/pageSize)+1;
    }


    public Pager(List<T> l, int pageSize)
    {
        _list = l;
        this.pageSize = pageSize;
        currentPage=1;
        lastPage = (l.size()/pageSize)+1;
    }


    public List<T> getPage(String pagina)
    {
        int tmp = Integer.parseInt(pagina);

        return getPage(tmp);
    }

    public List<T> getPage(int pagina)
    {
        ArrayList<T> l = new ArrayList<T>();


        if (pagina >= lastPage)
            pagina = lastPage;

        if (pagina <= 1)
            pagina =1;

        int firstIndex  = (pageSize * (pagina-1));

        for (Iterator i= this._list.listIterator(firstIndex);i.hasNext()&&l.size()<pageSize;)
        {
            T obj = (T)i.next();
            l.add( obj );
        }

//System.out.println("PRE-> CurrentPage= " + currentPage + ". PaginaSolicitada=" + pagina);
        currentPage = pagina;
//System.out.println("POST-> CurrentPage= " + currentPage + ". PaginaSolicitada=" + pagina);
        return l;
    }


    public int getFirstPageNumber(){
        return 1;
    }

    public int getLastPageNumber(){
        return this.lastPage;
    }

    public int getNextPageNumber(){
        return currentPage==lastPage?lastPage:currentPage+1;
    }

    public int getPreviousPageNumber(){
        return currentPage == 1 ? 1: currentPage -1;
    }

    public int getCurrentPageNumber()
    {
        return currentPage;
    }
}
